package common.validation;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * Created by aceyin on 15/6/24.
 */
public class ManualValidator {
    private static final Logger LOGGER = LoggerFactory.getLogger(ManualValidator.class);
    private Object bean;
    private Class clazz;
    private ValidationResult result;
    private static String MSG_NULL = "{manual.validator.property.%s.is.null}";
    private static String MSG_BLANK = "{manual.validator.property.%s.is.blank}";
    private static String LESS_THAN_MIN = "{manual.validator.property.%s.is.less.than.%s}";
    private static String GREATER_THAN_MAX = "{manual.validator.property.%s.is.greater.than.%s}";

    private ManualValidator(Object bean) {
        this.bean = bean;
        this.clazz = bean.getClass();
        this.result = new ValidationResult(true, "");
    }

    public static ManualValidator create(Object bean) {
        return new ManualValidator(bean);
    }

    /**
     * Validate property is not null.
     *
     * @param property
     * @return
     */
    public ManualValidator notNull(String property) {
        Object value = getPropertyValue(property);
        if (null == value) {
            setFail(MSG_NULL, property);
        }
        return this;
    }

    /**
     * Validate property not blank, only for String object.
     *
     * @param property
     * @return
     */
    public ManualValidator notBlank(String property) {
        Object value = getPropertyValue(property);
        if (value == null) {
            setFail(MSG_BLANK, property);
            return this;
        }
        if (value instanceof CharSequence) {
            if (StringUtils.isBlank((CharSequence) value)) {
                setFail(MSG_BLANK, property);
            }
            return this;
        } else {
            throw new RuntimeException("Property " + property + " is not a CharSequence instance");
        }
    }

    /**
     * Validate if the property value is smaller than the given value.
     *
     * @param property
     * @param min
     * @return
     */
    public ManualValidator gt(String property, int min) {
        Object value = getPropertyValue(property);
        if (value == null) {
            setFail(LESS_THAN_MIN, property, String.valueOf(min));
            return this;
        }
        if (value instanceof Number) {
            Number n = (Number) value;
            if (n.intValue() - min <= 0) {
                setFail(LESS_THAN_MIN, property, String.valueOf(min));
            }
            return this;
        } else {
            throw new RuntimeException("Property " + property + " is not a number.");
        }
    }


    /**
     * Validate if the property value is greater than the given value.
     *
     * @param property
     * @param max
     * @return
     */
    public ManualValidator lt(String property, int max) {
        Object value = getPropertyValue(property);
        if (value == null) {
            setFail(GREATER_THAN_MAX, property, String.valueOf(max));
            return this;
        }
        if (value instanceof Number) {
            Number n = (Number) value;
            if (n.intValue() - max >= 0) {
                setFail(GREATER_THAN_MAX, property, String.valueOf(max));
            }
            return this;
        } else {
            throw new RuntimeException("Property " + property + " is not a number.");
        }
    }

    public ValidationResult validate() {
        return result;
    }


    private Object getPropertyValue(String property) {
        try {
            Field f = ReflectionUtils.findField(clazz, property);
            f.setAccessible(true);
//            Field field = clazz.getDeclaredField(property);
            Object value = ReflectionUtils.getField(f, bean);
            return value;
//            field.setAccessible(true);
//            return field.get(bean);
        } catch (Exception e) {
            LOGGER.error("Error while get property", e);
            throw new RuntimeException(e);
        }
    }


    private void setFail(String msgTpl, String... property) {
        result.setSuccess(false);
        result.setMessage(String.format(msgTpl, property));
    }
}
